package Chuong06;

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;

public class Bai02  extends JFrame implements Runnable{

	public static void main(String[] args) {
		Bai02 fr = new Bai02();
		fr.setVisible(true);
		fr.setSize(500, 400);
	}
	
	int x=0,y=0; //toa do phat cua bong
	int dx,dy;//buoc chay cua qua bong theo chieu ngang
	int td = 10;// Toc do chay cua bong
		
	JPanel canvas = new JPanel();
	JPanel panel = new JPanel();
	
	JButton
			btnThem = new JButton("Thêm bóng"),
			btnTang = new JButton("Tăng tốc"),
			btnGiam = new JButton("Giảm tốc");
	int sl = 0;
	JLabel lblSoLuong = new JLabel("Số lượng quả bóng: "+sl+" quả");
	
	public Bai02(){
		super("Bài 02 - Chương 06");
		
		add(canvas);
		canvas.setBackground(Color.white);
		add(panel, BorderLayout.SOUTH);
		panel.add(btnThem);
		panel.add(btnTang);
		panel.add(btnGiam);
		panel.add(lblSoLuong);
		
		
		btnThem.addActionListener(new ActionListener() {
			
			public void actionPerformed(ActionEvent e) {
				sl++;
				String str="Số lượng quả bóng: "+sl+" quả";
				lblSoLuong.setText(str);	
				dx=1; dy =1; 
				x = 60; y = 60;
				
				new Thread(Bai02.this).start();
			}
		});
		
		btnTang.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				td -=3;	
			}
		});
		
		btnGiam.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				td +=3;		
			}
		});
	
	}
	
	public void run(){
		
		Graphics g = canvas.getGraphics();
		Color c = new Color((int)(255.0*Math.random()),(int)(255.0*Math.random()),(int)(255.0*Math.random()));
		int x=this.x,y=this.y, dx=this.dx, dy=this.dy;
		
		while(true){
			
				//g.setColor(new Color((float)Math.random(),(float)Math.random(),(float)Math.random()));
				g.setColor(c);
				g.fillOval(x, y, 20, 20);
				
				try{ 
					Thread.sleep(td);
				}
				catch(Exception e){}
				
				g.setColor(canvas.getBackground());
				g.fillOval(x, y, 20, 20);
			
				x += dx; y += dy;
				if(x<0 || x>canvas.getWidth()-20) dx=-dx;
				if(y<0 || y>canvas.getHeight()-20) dy=-dy;
			
			}
		}

}
